var express = require('express');
var fs = require('fs');
var mysql = require('mysql');
var ejs = require('ejs');

var router = express.Router();

// 连接 MySQL 数据库
var client = mysql.createConnection({
    host: 'localhost',
    port: "3306",
    user: 'root',
    password: '123456',
    database: 'library'
});

// 判断数据库是否连接成功
client.connect(function (err) {
    if (err) {
        console.log('[query] - : ' + err);
        return;
    }
    console.log('[connection connect]  MySQL数据库连接成功!');
});

// 显示注册页面
router.get('/', function (request, response) {
    response.render('login/register.ejs');
});

// 添加注册处理逻辑
router.post('/', function (request, response) {
    console.log(request.body);
        // 如果用户不存在，则插入新用户
        client.query('INSERT INTO user (username, password, nikename) VALUES (?, ?, ?)', [
            request.body.username, request.body.password, request.body.nikename
        ], function (insertErr) {
            if (insertErr) {
                console.log('[insert error] - :' + insertErr);
                    response.status(500).send('注册用户插入数据库出错');
                    return;
            }
            // 响应新注册用户
            response.render('home', {
                data: {
                    username: "新注册用户" + request.body.username
                }
            });
        });
            
    }); 
module.exports = router;